% This function generates one line of the simulation table on estimation
% and inference. The setting enters the function through the variable
% "settings".
function [output_test] = output_test_line(setting,n_sim,alpha_sig)

cd ../result
beta0_hat_vec = zeros(n_sim,1);
p_null_vec = zeros(n_sim,1);
p_adj_vec = zeros(n_sim,1);
l_alt = 4;
p_alt_vec = zeros(n_sim,l_alt);

i_real = 0;

for i_sim = 1 : n_sim
    s = ['results',num2str(i_sim),'.mat'];
    if exist(s, 'file') == 2
        i_real = i_real+1;
        load(s)
        eval(['output = output_',setting,';']);
        beta0_hat_vec(i_real) = output.estimate;
        p_null_vec(i_real) = output.p_null;
        p_alt_vec(i_real,:) = output.p_alt;
        p_adj_vec(i_real,:) = output.p_adj;
    end
end
cd ../output

load('../result/results7.mat')
switch lower(method)
    case 'ols'
        bias = mean(beta0_hat_vec);
        RMSE = sqrt(mean(beta0_hat_vec.^2));
    case 'iv'
        bias = median(beta0_hat_vec);
        RMSE = mean(abs(beta0_hat_vec));
end

rej_rate_null = mean(p_null_vec<p_adj_vec); % size
rej_rate_alt = mean(p_alt_vec<repmat(p_adj_vec,1,l_alt)); % power

% adjused p-value threshold such that empirical rejection rate is alpha_sig
alpha_adjusted = quantile(p_null_vec,alpha_sig); 
% adjusted power
power_adjusted = mean(p_alt_vec<alpha_adjusted+eps);

output_test = [bias,RMSE,rej_rate_null,rej_rate_alt,power_adjusted];




